using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

using DL_Monster_Mash_WCF_Streamed;
using System.Xml;
using System.Configuration;


namespace MonsterMashGame2
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class PickScreen : Microsoft.Xna.Framework.GameComponent
    {

        protected SpriteBatch spriteBatch = null;
        protected Vector2 cursorPosition;
        protected Texture2D cursor = null;
        protected Texture2D dctmLogo = null;
        protected Texture2D atmosLogo = null;
        protected DocumentumObject[] ListOfDocumentumObjects = null;
        protected Vector2[] DocumentumObjects;
        protected Rectangle[] DocumentumRectangles;
        protected List<String> ListOfAtmosContent = new List<String>();
        protected Vector2[] AtmosObjects;
        protected Rectangle[] AtmosRectangles;
        protected int countOfDocumentumObjects = 0;
        protected int countOfAtmosObjects = 0;
        protected Boolean cursorOnDocumentum = false;
        protected Boolean cursorOnAtmos = false;
        protected Vector2 dctmPosition;
        protected Vector2 atmosPosition;
        protected Boolean screenReady = false;
        protected SpriteFont textFont = null;
        protected Rectangle cursorRectangle;
        protected XmlNodeList modelNodes;
        protected XmlDocument doc;

        public PickScreen(Game game, SpriteBatch gameSpriteBatch)
            : base(game)
        {
            // TODO: Construct any child components here
            spriteBatch = gameSpriteBatch;
            dctmPosition = new Vector2(5, 10);
            atmosPosition = new Vector2(Game.GraphicsDevice.Viewport.Width * 3 / 4, 10);
            cursorPosition = new Vector2(Game.GraphicsDevice.Viewport.Width / 5, Game.GraphicsDevice.Viewport.Height / 2);
            cursorRectangle = new Rectangle((int)cursorPosition.X, (int)cursorPosition.Y, 1, 1);
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            if (screenReady)
            {
                return;
            }

            // TODO: Add your initialization code here
            textFont = Game.Content.Load<SpriteFont>("Arial");
            cursor = Game.Content.Load<Texture2D>("EMC_Specialist");
            dctmLogo = Game.Content.Load<Texture2D>("documentumLogo");
            atmosLogo = Game.Content.Load<Texture2D>("atmosLogo");

            MonsterMashStreamingServiceClient dctmClient = new MonsterMashStreamingServiceClient();
            String sQualifier = "SELECT * FROM dl_model WHERE ANY v_textures IS NOT NULL";

            try
            {
                ListOfDocumentumObjects = dctmClient.GetListOfRepositoryObjects(sQualifier);
            }
            catch (Exception ex)
            {

            }

            //get information from Atmos service:
            String RegistryDB = ConfigurationManager.AppSettings["Registry"];
            String RegistryUsername = ConfigurationManager.AppSettings["RegistryUsername"];
            String RegistryPassword = ConfigurationManager.AppSettings["RegistryPassword"];
            XhiveServerSessionIfClient xDBClient = new XhiveServerSessionIfClient();
            String sessionID = xDBClient.connect(RegistryUsername, RegistryPassword, RegistryDB);

            String linksDoc = null;

            try
            {
                linksDoc = xDBClient.getDocument(sessionID, "/xbox1/links.xml", null, null);
            }
            catch (Exception ex1)
            {

            }

            if (String.IsNullOrEmpty(linksDoc))
            {
                return;
            }

            doc = new XmlDocument();
            doc.LoadXml(linksDoc);

            modelNodes = doc.GetElementsByTagName("Model");

            foreach (XmlNode modelNode in modelNodes)
            {
                XmlAttribute modelName = modelNode.Attributes["Name"];
                ListOfAtmosContent.Add(modelName.Value);
            }

            countOfDocumentumObjects = ListOfDocumentumObjects.Count();
            DocumentumObjects = new Vector2[countOfDocumentumObjects];
            DocumentumRectangles = new Rectangle[countOfDocumentumObjects];
            for (int i = 0; i < countOfDocumentumObjects; i++)
            {
                DocumentumObjects[i] = new Vector2(5, 15 + (i * 20));
                DocumentumRectangles[i] = new Rectangle();
                DocumentumRectangles[i].X = (int)DocumentumObjects[i].X;
                DocumentumRectangles[i].Y = (int)DocumentumObjects[i].Y;
                DocumentumRectangles[i].Width = 50;
                DocumentumRectangles[i].Height = 20;
            }

            countOfAtmosObjects = ListOfAtmosContent.Count;
            AtmosObjects = new Vector2[countOfAtmosObjects];
            AtmosRectangles = new Rectangle[countOfAtmosObjects];
            for (int i = 0; i < countOfAtmosObjects; i++)
            {
                AtmosObjects[i] = new Vector2(Game.GraphicsDevice.Viewport.Width * 3 / 4, 15 + (i * 20));
                AtmosRectangles[i] = new Rectangle();
                AtmosRectangles[i].X = (int)AtmosObjects[i].X;
                AtmosRectangles[i].Y = (int)AtmosObjects[i].Y;
                AtmosRectangles[i].Width = 50;
                AtmosRectangles[i].Height = 20;
            }

            base.Initialize();

            screenReady = true;

        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                cursorPosition.Y--;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                cursorPosition.Y++;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                cursorPosition.X--;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                cursorPosition.X++;
            }
            //if (cursorPosition.X <= dctmPosition.X)
            //{
            //    cursorOnDocumentum = true;
            //}
            //else if (cursorPosition.X >= atmosPosition.X)
            //{
            //    cursorOnAtmos = true;
            //}
            //else
            //{
            //    cursorOnAtmos = false;
            //    cursorOnDocumentum = false;
            //}

            cursorRectangle.X = (int)cursorPosition.X;
            cursorRectangle.Y = (int)cursorPosition.Y;

            CurrentState.State = GameState.PickScreen;

            if (Keyboard.GetState().IsKeyDown(Keys.Enter))
            {
                for (int i = 0; i < countOfDocumentumObjects; i++)
                {
                    if (DocumentumRectangles[i].Intersects(cursorRectangle))
                    {
                        CurrentState.State = GameState.DocumentumScreen;
                        CurrentState.DocumentumObjectID = ListOfDocumentumObjects[i].ID;
                        base.Update(gameTime);
                        return;
                    }
                }
                for (int i = 0; i < countOfAtmosObjects; i++)
                {
                    if (AtmosRectangles[i].Intersects(cursorRectangle))
                    {
                        CurrentState.State = GameState.AtmosScreen;
                        CurrentState.AtmosModel = ListOfAtmosContent[i];
                        foreach (XmlNode modelNode in modelNodes)
                        {
                            if (modelNode.Attributes["Name"].Value.Equals(ListOfAtmosContent[i]))
                            {
                                XmlNodeList modelTextures = modelNode.ChildNodes;
                                XmlNode modelTexture = modelTextures[0];
                                if (null != modelTexture)
                                {
                                    CurrentState.AtmosTexture1 = modelTexture.InnerText;
                                }
                                modelTexture = modelTextures[1];
                                if (null != modelTexture)
                                {
                                    CurrentState.AtmosTexture2 = modelTexture.InnerText;
                                }
                                modelTexture = modelTextures[2];
                                if (null != modelTexture)
                                {
                                    CurrentState.AtmosTexture3 = modelTexture.InnerText;
                                }
                            }
                        }
                        base.Update(gameTime);
                        return;
                    }
                }
            }

            base.Update(gameTime);
        }

        public void Draw()
        {
            if ( (null == ListOfDocumentumObjects  || ListOfDocumentumObjects.Count() == 0)
                && (null == ListOfAtmosContent || ListOfAtmosContent.Count == 0) )
            {
                return;
            }

            spriteBatch.Draw(cursor, cursorPosition, Color.White);
            //spriteBatch.Draw(dctmLogo, dctmPosition, Color.White);
            spriteBatch.Draw(atmosLogo, atmosPosition, Color.White);

            for (int i = 0; i < countOfDocumentumObjects; i++)
            {
                if (DocumentumRectangles[i].Intersects(cursorRectangle))
                {
                    spriteBatch.DrawString(textFont, ListOfDocumentumObjects[i].Name, DocumentumObjects[i], Color.Red);
                }
                else
                {
                    spriteBatch.DrawString(textFont, ListOfDocumentumObjects[i].Name, DocumentumObjects[i], Color.Green);
                }
            }
            for (int i = 0; i < countOfAtmosObjects; i++)
            {
                if (AtmosRectangles[i].Intersects(cursorRectangle))
                {
                    spriteBatch.DrawString(textFont, ListOfAtmosContent[i], AtmosObjects[i], Color.Red);
                }
                else
                {
                    spriteBatch.DrawString(textFont, ListOfAtmosContent[i], AtmosObjects[i], Color.Green);
                }
            }


        }

    }
}